package cn.xiaohaoo.datacollection;

import cn.xiaohaoo.medicine.util.mongo.MongoDatabaseUtils;
import org.bson.Document;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 爬取网站 http://www.zhongyoo.com/name/
 */
public class MedicineOutlinePageProcessor implements PageProcessor {
    @Override
    public void process(Page page) {
        //爬取列表页
        if (page.getUrl().toString().endsWith("name/")) {
            for (Selectable selectable : page.getHtml().$(".all").nodes()) {
                String name = selectable.xpath("a/text()").toString();
                String href = selectable.xpath("a/@href").toString();
                page.addTargetRequest(href);
            }
        } else {
            //爬取详细页
            String firstClass = page.getHtml().$(".listT1").xpath("b/h1/text()").toString();
            //页面数据处理部分
            List<Map<String, Object>> names = new ArrayList<>();
            page.getHtml().$(".jbLetCon").xpath("dl").nodes().forEach(data -> {
                //中药归类信息
                for (Selectable li : data.xpath("dd/ul/li").nodes()) {
                    String url = li.xpath("a/@href").toString();
                    String name = li.xpath("a/text()").toString();

                    Map<String, Object> medicineOutlineByName = getMedicineOutlineByName(name);
                    if (medicineOutlineByName != null) {
                        Map<String, Object> imgMap = new HashMap<>();
                        imgMap.put("text", name);
                        imgMap.put("icon", medicineOutlineByName.get("img"));
                        names.add(imgMap);
                    }
                }
            });
            Document document = new Document().append("name", firstClass).append("details", names);
            MongoDatabaseUtils.insertDocument(MongoDatabaseUtils.MEDICINE_DETAIL_COLLECTION, document);
        }
    }

    @Override
    public Site getSite() {
        return new Site().setTimeOut(20 * 1000);
    }

    public static void main(String[] args) {
        LocalDateTime begin = LocalDateTime.now();
        Spider.create(new MedicineOutlinePageProcessor()).addUrl("http://www.zhongyoo.com/name/")
            .thread(15).run();
        System.out.println("爬取用时：" + Duration.between(begin, LocalDateTime.now()).toMinutes() + "分钟");
    }


    private Map<String, Object> getMedicineOutlineByName(String name) {
        return MongoDatabaseUtils.queryDocumentByName(MongoDatabaseUtils.MEDICINE_DETAIL_COLLECTION,
            new Document().append("name", name));
    }
}
